using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerLedgeClimbState : PlayerClimbState
{
    public PlayerLedgeClimbState(Player player, PlayerMoveData playerData, StateMachine stateMachine, string animBoolName) : base(player, playerData, stateMachine, animBoolName)
    {
    }

    private Vector2 detecedPos;
    private Vector2 cornerPos;
    private Vector2 startPos;
    private Vector2 endPos;

    private bool isHolding;
    private bool isClimbing;

    public override void Enter()
    {
        base.Enter();
        isHolding = true;
        isClimbing = false;
        player.SetVelocityZero();
        player.transform.position = detecedPos;
        cornerPos = player.CalculateCorner();

        startPos = cornerPos + new Vector2(playerData.startOffset.x * player.FacingDirection, playerData.startOffset.y);
        endPos = cornerPos + new Vector2(playerData.endOffset.x * player.FacingDirection, playerData.endOffset.y);

        player.transform.position = startPos;
    }

    public void SetdetecedPos(Vector3 detecedPos) { this.detecedPos = detecedPos; }

    public override void LogicUpdate()
    {
        base.LogicUpdate();

        Debug.DrawLine(cornerPos, cornerPos + new Vector2(0, 0.1f));
        Debug.DrawLine(cornerPos, cornerPos + new Vector2(0.1f * -player.FacingDirection, 0));

        player.SetVelocityZero();
        player.transform.position = startPos;
        if (isHolding) 
        {
            if (xInput == player.FacingDirection)
            {
                isClimbing = true;
                isHolding = false;
                player.animator.Play("LedgeClimb");
            }
            else if (yInput == -1) 
            {
                stateMachine.ChangeState(player.InAirState);
            }
            else if (jumpInput)
            {
                stateMachine.ChangeState(player.WallNegativeJumpState);
            }

        }

        if (isClimbing) 
        {
            if (isAnimationFinish)
            {
                player.transform.position = endPos;

                if (CheckIsTouchingCeiling())
                {
                    stateMachine.ChangeState(player.CrouchIdleState);
                }
                else 
                {
                    stateMachine.ChangeState(player.IdleState);
                }
            }
        }
           
    }


    private bool CheckIsTouchingCeiling() 
    {
        RaycastHit2D hit2D = Physics2D.Raycast(cornerPos + new Vector2(0.015f * player.FacingDirection, 0), Vector2.up, 1.6f, playerData.groundLayer);
        Debug.DrawLine(cornerPos, cornerPos + Vector2.up * 1.6f, Color.red);
        return hit2D;
    }
}
